package com.spring.ast.service;

import com.spring.ast.annotated.Describe;
import com.spring.ast.annotated.Relation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.annotation.Annotation;

/**
 * @author liuzhiqiang
 */
@Component
@Slf4j
public class ExchangeUtil {

    private static ExchangeService exchangeService;
    @Resource
    private ExchangeService service;

    public static String describeHandle(Describe describe, Object value) {
        try {
            if (ExchangeUtil.exchangeService != null) {
                return ExchangeUtil.exchangeService.describeHandle(describe, value);
            } else {
                return "";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return "";
        }
    }

    public static String relationHandle(Relation relation, Object value) {
        try {
            if (ExchangeUtil.exchangeService != null) {
                return ExchangeUtil.exchangeService.relationHandle(relation, value);
            } else {
                return "";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return "";
        }
    }

    @PostConstruct
    public void init() {
        ExchangeUtil.exchangeService = this.service;
    }

    public static Relation createRelation(String table,String showField,String targetField,String[] args, String alias) {
        return new Relation(){

            @Override
            public Class<? extends Annotation> annotationType() {
                return Relation.class;
            }

            @Override
            public String table() {
                return table;
            }

            @Override
            public String showField() {
                return showField;
            }

            @Override
            public String targetField() {
                return targetField;
            }

            @Override
            public String[] args() {
                return args;
            }

            @Override
            public String alias() {
                return alias;
            }
        };
    }
    public static Describe createDescribe(String[] args, String type, String alias) {
        return new Describe(){

            @Override
            public Class<? extends Annotation> annotationType() {
                return Describe.class;
            }

            @Override
            public String type() {
                return type;
            }

            @Override
            public String[] args() {
                return args;
            }

            @Override
            public String alias() {
                return alias;
            }
        };
    }
}
